﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CarolLib;
using CarolLib.Configuration;
using CarolLib.WinService;
using DispatchAssist.BusinessLogical.BLL;
using DispatchAssist.BusinessLogical.Model;
using DispatchAssist.Model;
using System.Xml;

namespace DispatchAssist.ACARSSender
{
   public class Sender:IBasicTask
    {
        #region members

        static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

       // private static readonly int MaxCharsNumber = 1000;

        private static MessageCreateManger manger;

        private static string TemplateXml;

        #endregion

        #region IBasicTask
        public void Init()
        {
            manger = new MessageCreateManger();

            GetTemplateXml();
        }

        public void Execute()
        {
             //step 1. get all send list

            List<ACARSMsg> sendList;
            try
            {
                sendList = manger.GetUnSendAcarsMsg();

                Logger.InfoFormat("there are {0} messages need to send",sendList.Count);
            }
            catch (Exception e)
            {
                Logger.Error("get unsend Acars Message Error",e);
                return;
            }

            if (sendList == null || sendList.Count == 0)
            {
                return;
            }

            //step 2. 生成标准格式的xml

            foreach (ACARSMsg sendModel in sendList)
            {
                try
                {
                    //根据模板生成xml字符串
                    string xmlStr = string.Format(TemplateXml, GetFormateTailNo(sendModel.ReceiveTailNo), sendModel.NeedNullSet, sendModel.RcvAddress, sendModel.SendAddress, sendModel.Smi, sendModel.NeedReceipt, sendModel.MsgBody, "");


                    // 保存到共享目录
                    XmlDocument doc = new XmlDocument();

                    doc.LoadXml(xmlStr);
                    
                    string fileName=GetSingleFileName(".xml");

                    doc.Save(System.Configuration.ConfigurationManager.AppSettings["AcarsXmlPath"]+fileName);

                    //标志状态
                    sendModel.MsgStatus = (int)Enums.MessageStatus.FinishSend;

                    Logger.WarnFormat("AcarsMsgID: {0} ,Xml File Name: {1}", sendModel.ACARSMsgID, fileName);

                }
                catch (Exception e)
                {
                    Logger.Error(string.Format("create xml error,MsgID:{0}",sendModel.ACARSMsgID),e);

                    sendModel.MsgStatus = (int)Enums.MessageStatus.SendError;

                    continue;
                }
            }

            Logger.InfoFormat("send success");

            //step 3. update status
            try
            {
                manger.UpdateAcarsMsgStatus(sendList);
            }
            catch (Exception e)
            {
                Logger.Error("error in update Acars Msg Status after Send", e);
            }

            Logger.InfoFormat("update status success");
            
        }

        public void Exit()
        {
            
        }

        #endregion

        #region private method

        private void GetTemplateXml()
        {
            XmlDocument doc = new XmlDocument();

           // Logger.Info(System.w);
           
            doc.Load(System.Configuration.ConfigurationManager.AppSettings["AcarsTemplateXmlPath"]);

            TemplateXml= doc.OuterXml;
        }

        private string GetSingleFileName(string extension)
        {
            return Guid.NewGuid().ToString()+extension;
        }

        private string GetFormateTailNo(string tailNo)
        {
            if (tailNo[1] == '-')
            {
                return tailNo;
            }
            else
            {
              return  tailNo.Insert(1, "-");
            }
        }

        #endregion
    }

}
